package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reggie.common.R;
import com.reggie.dto.DishDto;
import com.reggie.entity.Category;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.service.CategoryService;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostMapping
    public R<String> save(@RequestBody DishDto dishdto) {
        dishService.saveDish(dishdto);
        return R.success("新增成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        // 构造分页对象，构造条件，添加条件，排序
        Page<Dish> ipage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name != null, Dish::getName, name);
        lambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        // 添加菜品分类
        dishService.page(ipage, lambdaQueryWrapper);

        // 添加属性
        Page<DishDto> pageInfo = new Page<>();

        List<Dish> records = ipage.getRecords();
        List<DishDto> dishDtoRecords = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            // 查找赋值
            BeanUtils.copyProperties(item, dishDto);
            if(category != null) {
                dishDto.setCategoryName(category.getName());
            }else {
                dishDto.setCategoryName("未知");
            }
            return dishDto;
        }).toList();

        BeanUtils.copyProperties(ipage, pageInfo, "records");
        pageInfo.setRecords(dishDtoRecords);

        return R.success(pageInfo);
    }

    // 多表的增加修改，删除。最好在service里写，然后加事务。
    // 一个查询可以直接写在controller中
    @GetMapping("{id}")
    public R<DishDto> getDishDto(@PathVariable Long id) {
        // 查询菜品
        Dish dish = dishService.getById(id);
        Long categoryId = dish.getCategoryId();
        // 查询类别
        Category category = categoryService.getById(categoryId);
        // 查询口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);

        // 封装到dishDto中
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        dishDto.setCategoryName(category.getName());
        dishDto.setFlavors(list);
        return R.success(dishDto);
    }

    @PutMapping
    public R<String> updateDishDto(@RequestBody DishDto dishDto) {
        dishService.updateDish(dishDto);


        // 清理所有菜品类别的缓存
        // Set keys = redisTemplate.keys("dish_*");
        // redisTemplate.delete(keys);

        // 清理一个类别的缓存
        String keys = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(keys);

        return R.success("修改成功");
    }

    // // 后台版
    // @GetMapping("list")
    // public R<List<Dish>> queryList(Dish dish) {
    //     // 根据菜品类别，查询这一类别的菜品
    //     LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
    //     dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
    //     dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
    //     List<Dish> list = dishService.list(dishLambdaQueryWrapper);
    //     return R.success(list);
    // }

    // 前端版
    @GetMapping("list")
    public R<List<DishDto>> queryList(Dish dish) {
        List<DishDto> dishDtos = null;
        // 如果缓存中存在
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        // 如果缓存不存在
        // 根据菜品类别，查询这一类别的菜品
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
        dishLambdaQueryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);

        // 封装成DishDto对象
        dishDtos = dishList.stream().map((item) -> {
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list = dishFlavorService.list(lambdaQueryWrapper);

            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            dishDto.setFlavors(list);
            return dishDto;
        }).toList();

        redisTemplate.opsForValue().set(key, dishDtos, 60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}










